#include "IndexBufferGLES.h"
#include "RendererGLES.h"

namespace Nezha
{

	IndexBufferGLES::IndexBufferGLES(HardwareBuffer::Usage usage, IndexBuffer::IndexType it, u32 numIndices ,RendererGLES* r, u16* data)
		:IndexBuffer(usage, it, numIndices, true)
		,mRenderer(r)
	{
		glGenBuffers(1, &mGLBufferId);
		GL_ERROR_DUMP(mRenderer->getAdaptor());

		mShadowBuffer.write((u8*)data, mSizeInBytes);
		mRenderer->bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLBufferId);

		glBufferData(GL_ELEMENT_ARRAY_BUFFER, mSizeInBytes, (void*)data, GLenumMapping::BufferUsage(mUsage));
		GL_ERROR_DUMP(mRenderer->getAdaptor());
	}

	IndexBufferGLES::~IndexBufferGLES()
	{
		glDeleteBuffers(1, &mGLBufferId);
		GL_ERROR_DUMP(mRenderer->getAdaptor());
	}

	void* IndexBufferGLES::lockImpl(u32 offset, u32 length, LockOption opt)
	{
		NZ_ASSERT_EX(false, "Opengl es2 support no hardware buffer locking, please check the shadow buffer locking issue.");

		return NULL;
	}

	void IndexBufferGLES::unlockImpl()
	{
		// do nothing.
	}


	void IndexBufferGLES::syncShadowBuffer()
	{
		mRenderer->bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLBufferId);

		glBufferData(GL_ELEMENT_ARRAY_BUFFER, mSizeInBytes, mShadowBuffer.data(), GLenumMapping::BufferUsage(mUsage));
		GL_ERROR_DUMP(mRenderer->getAdaptor());
	}
}